package com.tpshion.cloud.core.interceptor;

import com.tpshion.cloud.common.support.Assert;
import com.tpshion.cloud.common.support.ErrorCode;
import com.tpshion.cloud.core.annotation.Permission;
import com.tpshion.cloud.core.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(PermissionInterceptor.class);

    @Autowired
    private AuthService authService;

    @Value("${spring.application.name:unknow}")
    private String sysCode;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求类型
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            return true;
        }

        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Permission permission = handlerMethod.getMethodAnnotation(Permission.class);
        if(null != permission){
            log.info("*** 权限验证 [{}] {}",request.getMethod(),request.getServletPath());
            String authName = permission.value();
            Assert.isTrue(authService.permission(authName,sysCode).isStatus(),ErrorCode.NO_ACCESS);
        }
        return true;
    }
}
